import type { RouteRecordStringComponent } from '@vben/types'
import type { RouteMeta } from 'vue-router'

import { requestClient } from '#/api/request'
import { treeMap } from '#/helper/treeHelper'

export namespace MenuListApi {
    export interface RouteItem {
        path: string
        component: string
        meta: RouteMeta
        name?: string
        title?: string
        alias?: string | string[]
        redirect?: string
        caseSensitive?: boolean
        children?: RouteItem[]
        checkedList?: RouteItem[]
        status: 0 | 1
        type: 0 | 1
        icon?: string
    }

    /**
     * @description: Get menu return value
     */
    export type getMenuListResultModel = RouteItem[]
}

const isMenu = (type: number) => type === 0
/**
 * 获取用户所有菜单
 */
export async function getAllMenusApi() {
    return requestClient.get<RouteRecordStringComponent[]>('/index/getMenuList').then((res) => {
        // 嵌套层级第一层component需要有值
        res.forEach((v) => {
            v.component = v.component || 'BasicLayout'
        })

        res = treeMap(res, {
            conversion(data: MenuListApi.getMenuListResultModel[number]) {
                // 兼容老的模板 文件结构没有使用index.vue 作为页面的入口  由于服务端初始的路由没有带index 新版需要加上
                if (['/system/menu', '/system/role', '/system/user'].includes(data.component)) {
                    data.component += '/index'
                }

                if (data.children?.length) {
                    // 是否有子页面
                    const menuList = data.children.filter((v) => isMenu(v.type))
                    // 当前为父级设置了组件地址， 需要移植到子节点第一个 否则导致页面重定向错误
                    if (menuList.length > 0 && (data.component || '').includes('/')) {
                        const redirect = `${data.path}/index`
                        data.children.unshift({
                            ...data,
                            path: redirect,
                            component: data.component,
                            children: [],
                            status: 0
                        })
                        // 重新定义组件地址
                        data.component = ''
                        data.redirect = redirect
                    }
                }

                return {
                    ...data,
                    meta: {
                        ...data.meta,
                        title: data.meta?.title || data.title,
                        hideInMenu: data?.status !== 1,
                        icon: data.meta?.icon || data?.icon
                    },
                    name: data.name || data.path || ''
                }
            }
        })

        return res
    })
}
